<template>
  <div class="markdown-editor" :class="{ 'focus-mode': focusMode }">
    <md-editor
      v-model="localValue"
      :theme="computedTheme"
      :toolbars="toolbars"
      :placeholder="placeholder"
      :height="height"
      :preview-theme="previewTheme"
      :code-theme="codeTheme"
      :page-fullscreen="pageFullscreen"
      :preview="preview"
      :html-preview="htmlPreview"
      :no-fullscreen="noFullscreen"
      @on-change="handleChange"
      @on-save="$emit('save', $event)"
      @on-html-changed="$emit('html-changed', $event)"
      @on-get-catalog="$emit('get-catalog', $event)"
      @on-focus="$emit('focus', $event)"
      @on-blur="$emit('blur', $event)"
      @on-error="$emit('error', $event)"
      @on-upload-img="handleUploadImg"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { MdEditor, config } from 'md-editor-v3';
import type { ToolbarNames, GlobalConfig } from 'md-editor-v3';
import MarkExtension from 'markdown-it-mark';
import LinkAttr from 'markdown-it-link-attributes';

// 导入样式
import 'md-editor-v3/lib/style.css';
import '@vavt/cm-extension/dist/previewTheme/arknights.css';

// 配置md-editor-v3
const globalConfig: Partial<GlobalConfig> = {
  // 代码高亮配置
  editorExtensions: {
    highlight: {
      css: {
        atom: {
          light:
            'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-light.min.css',
          dark: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css'
        }
      }
    }
  },
  // 编辑器配置
  editorConfig: {
    renderDelay: 0,
    zIndex: 1
  },
  // Markdown-it配置
  markdownItConfig: (md, { editorId }) => {
    // 添加自定义markdown-it插件
    try {
      md.use(MarkExtension);
      md.use(LinkAttr, {
        attrs: {
          target: '_blank',
          rel: 'noopener noreferrer'
        }
      });
    } catch (error) {
      console.warn('Failed to load markdown-it plugins:', error);
    }
  }
};

// 应用配置
config(globalConfig);

// 组件属性
interface Props {
  modelValue: string;
  theme?: 'light' | 'dark';
  placeholder?: string;
  height?: string | number;
  toolbars?: ToolbarNames[];
  previewTheme?: string;
  codeTheme?: string;
  pageFullscreen?: boolean;
  preview?: boolean;
  htmlPreview?: boolean;
  focusMode?: boolean;
  sanitizeHtml?: (html: string) => string;
  noFullscreen?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  theme: 'light',
  placeholder: '在这里写下你的想法...',
  height: '100%',
  toolbars: () => [
    'bold',
    'italic',
    'underline',
    'strike-through',
    'title',
    'quote',
    'unordered-list',
    'ordered-list',
    'code-row',
    'code',
    'link',
    'image',
    'table',
    'revoke',
    'next',
    'save',
    'preview',
    'html-preview',
    'catalog'
  ],
  previewTheme: 'arknights',
  codeTheme: 'atom',
  pageFullscreen: false,
  preview: true,
  htmlPreview: false,
  focusMode: false,
  noFullscreen: true,
  sanitizeHtml: (html: string) => html
});

// 事件定义
const emit = defineEmits<{
  'update:modelValue': [value: string];
  change: [value: string];
  save: [value: string, html: Promise<string>];
  'html-changed': [html: string];
  'get-catalog': [catalog: any[]];
  focus: [event: FocusEvent];
  blur: [event: FocusEvent];
  error: [error: any];
  'upload-img': [files: File[], callback: (urls: any[]) => void];
}>();

// 本地值引用
const localValue = ref(props.modelValue);

// 监听外部prop变化，同步到本地值
watch(
  () => props.modelValue,
  newValue => {
    localValue.value = newValue;
  }
);

// 计算实际使用的主题
const computedTheme = computed(() => {
  if (props.focusMode) {
    return 'dark';
  }
  return props.theme;
});

// 处理内容变化
const handleChange = (value: string) => {
  emit('update:modelValue', value);
  emit('change', value);
};

// 处理图片上传
const handleUploadImg = (files: File[], callback: (urls: any[]) => void) => {
  emit('upload-img', files, callback);
};
</script>

<style scoped lang="scss">
.markdown-editor {
  height: 100%;
  width: 100%;
  background: transparent;

  :deep(.md-editor) {
    height: 100%;
    max-height: 100%;
    border: none;
    border-radius: 0;
    background: transparent;
    font-family:
      -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
    overflow: hidden;
    z-index: 1;
    position: relative;

    .md-editor-header {
      border-bottom: 1px solid rgba(0, 0, 0, 0.08);
      background: rgba(250, 251, 252, 0.8);
      backdrop-filter: blur(10px);
      padding: 12px 24px;

      .md-editor-toolbar {
        border: none;
        background: transparent;

        .md-editor-toolbar-item {
          color: #5f6368;
          border-radius: 6px;
          transition: all 0.2s ease;
          font-size: 16px;

          &:hover {
            background: rgba(0, 0, 0, 0.05);
            color: #202124;
          }

          &.active {
            background: #e8f0fe;
            color: #1967d2;
          }
        }
      }
    }

    .md-editor-content {
      padding: 20px 0;
      max-width: 800px;
      margin: 0 auto;
      line-height: 1.7;
      height: calc(100% - 50px);
      max-height: calc(100% - 50px);
      overflow-y: auto;

      .md-editor-content-edit {
        padding: 0 48px;
        font-size: 16px;
        color: #202124;
        font-family:
          'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
        line-height: 1.8;

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
          color: #202124;
          font-weight: 600;
          margin: 24px 0 12px 0;
          line-height: 1.3;

          &:first-child {
            margin-top: 0;
          }
        }

        h1 {
          font-size: 2em;
        }
        h2 {
          font-size: 1.5em;
        }
        h3 {
          font-size: 1.25em;
        }
        h4 {
          font-size: 1.1em;
        }
        h5 {
          font-size: 1em;
        }
        h6 {
          font-size: 0.9em;
        }

        p {
          margin: 16px 0;
          color: #202124;
          line-height: 1.7;
        }

        pre {
          background: #f6f8fa;
          border: 1px solid rgba(0, 0, 0, 0.06);
          border-radius: 8px;
          padding: 16px;
          margin: 20px 0;
          font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
          font-size: 14px;
          line-height: 1.5;
          overflow-x: auto;
        }

        code {
          background: #f1f3f4;
          color: #d73a49;
          padding: 2px 4px;
          border-radius: 4px;
          font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
          font-size: 0.9em;
        }

        blockquote {
          border-left: 4px solid #1967d2;
          margin: 16px 0;
          padding: 12px 20px;
          background: rgba(25, 103, 210, 0.05);
          border-radius: 0 4px 4px 0;
          color: #5f6368;
        }

        ul,
        ol {
          margin: 16px 0;
          padding-left: 24px;

          li {
            margin: 6px 0;
            line-height: 1.6;
            color: #202124;
          }
        }

        a {
          color: #1967d2;
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }

        table {
          width: 100%;
          border-collapse: collapse;
          margin: 16px 0;

          th,
          td {
            padding: 8px 12px;
            text-align: left;
            border-bottom: 1px solid rgba(0, 0, 0, 0.08);
          }

          th {
            background: #f8f9fa;
            font-weight: 600;
            color: #202124;
          }
        }

        hr {
          border: none;
          height: 1px;
          background: rgba(0, 0, 0, 0.08);
          margin: 24px 0;
        }
      }

      .md-editor-content-preview {
        padding: 0 48px;
        font-family:
          -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial,
          sans-serif;

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
          color: #202124;
          font-weight: 600;
          margin: 24px 0 12px 0;
          line-height: 1.3;
        }

        p {
          color: #3c4043;
          line-height: 1.7;
          margin: 16px 0;
        }

        blockquote {
          border-left: 4px solid #1967d2;
          margin: 16px 0;
          padding: 12px 20px;
          background: rgba(25, 103, 210, 0.05);
          border-radius: 0 4px 4px 0;
          color: #5f6368;
        }
      }
    }

    // 暗色主题适配
    &[theme='dark'] {
      .md-editor-header {
        background: rgba(30, 30, 30, 0.8);
        border-bottom-color: rgba(255, 255, 255, 0.08);

        .md-editor-toolbar {
          .md-editor-toolbar-item {
            color: #9aa0a6;

            &:hover {
              background: rgba(255, 255, 255, 0.05);
              color: #e8eaed;
            }

            &.active {
              background: rgba(25, 103, 210, 0.2);
              color: #8ab4f8;
            }
          }
        }
      }

      .md-editor-content {
        .md-editor-content-edit {
          color: #e8eaed;

          h1,
          h2,
          h3,
          h4,
          h5,
          h6 {
            color: #e8eaed;
          }

          p {
            color: #e8eaed;
          }

          code {
            background: #37474f;
            color: #ff6b6b;
          }

          blockquote {
            border-left-color: #8ab4f8;
            background: rgba(138, 180, 248, 0.1);
            color: #9aa0a6;
          }

          a {
            color: #8ab4f8;

            &:hover {
              border-bottom-color: #8ab4f8;
            }
          }
        }
      }

      .md-editor-catalog {
        background: rgba(30, 30, 30, 0.8);
        border-right-color: rgba(255, 255, 255, 0.08);

        .md-editor-catalog-item {
          color: #9aa0a6;

          &:hover {
            color: #8ab4f8;
            background: rgba(138, 180, 248, 0.1);
          }

          &.active {
            color: #8ab4f8;
            background: rgba(138, 180, 248, 0.2);
            border-right-color: #8ab4f8;
          }
        }
      }
    }
  }
}

// 专注模式样式
.markdown-editor.focus-mode {
  :deep(.md-editor) {
    .md-editor-content {
      .md-editor-content-edit {
        font-size: 18px;
        line-height: 1.9;
        color: #dcdcdc;

        h1,
        h2,
        h3,
        h4,
        h5,
        h6 {
          color: #ffffff;
        }

        p {
          color: #dcdcdc;
        }
      }
    }
  }
}
</style>
